package jstudy.gu;

import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.dialects.MySqlDialect;

import springfox.documentation.swagger2.annotations.EnableSwagger2;


@EnableSwagger2
@SpringBootApplication
public class AppStarter {
	private static ConfigurableApplicationContext app;

	// 可能会抛出异常
	/**
	 * @param <T>
	 * @param clz
	 * @return 获取Class泛型对应的bean对象,可能会抛出异常. 当指定的bean 对象没有被Spring管理的时候,会抛出异常
	 */
	public static <T> T getBean(Class<T> clz) {
		return app.getBean(clz);
	}

	// 可能会抛出异常
	/**
	 * @param <T>
	 * @param clz
	 * @return 获取Class泛型对应的bean对象, 当指定的bean 对象没有被Spring管理的时候,会返回null
	 */
	public static <T> T tryGetBean(Class<T> clz) {
		try {
			return app.getBean(clz);
		} catch (Exception e) {
			return null;
		}
	}

	// 可能会抛出异常
	/**
	 * @param <T>
	 * @param clz
	 * @return 获取name对应的bean对象,可能会抛出异常. 当指定的 bean 对象没有被Spring管理的时候,会抛出异常
	 */
	public static <T> T getBean(String name) {
		return (T) app.getBean(name);
	}

	// 可能会抛出异常
	/**
	 * @param <T>
	 * @param clz
	 * @return 获取name对应的bean对象, 当指定的bean 对象没有被Spring管理的时候,会返回null
	 */
	public static <T> T tryGetBean(String name) {
		try {
			return getBean(name);
		} catch (Exception e) {
			return null;
		}
	}

	public static void main(String[] args) {
		app = SpringApplication.run(AppStarter.class, args);
	}

	@Bean
	public MybatisPlusInterceptor getInterceptor() {
		MybatisPlusInterceptor mpi = new MybatisPlusInterceptor();
		mpi.addInnerInterceptor(new PaginationInnerInterceptor(new MySqlDialect()));
		return mpi;
	}

	@Autowired
	private MessageSource messageSource;

	@Bean
	public Validator getValidator() {
		LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
		validator.setValidationMessageSource(this.messageSource);
		return validator;
	}
}
